package com.linln.admin.system.web;

import com.linln.admin.system.vos.ExpandCh;
import com.linln.admin.system.vos.ExpandChannel;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.quicks.beauty.server.vos.SourceFrom;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Controller
@RequestMapping(value = "/mains/expandCh")
public class ExpandChannelController {

    DateTimeFormatter datePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA);
    DateTimeFormatter dateTimePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

    @Autowired
    @Qualifier(value = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @ResponseBody
    @RequestMapping(value = "/save")
    public ResultVo addExpandCh(String channelName, String ch, String type, String exUrl) {
        ListOperations<String, Object> ofList = redisTemplate.opsForList();
        ExpandChannel channel = new ExpandChannel();
        channel.setId(UUID.randomUUID().toString());
        channel.setChannelName(channelName).setCh(ch).setType(type)
                .setExUrl(exUrl).setDates(LocalDateTime.now().format(dateTimePattern));
        Long parent = ofList.rightPush("expandChannelParent", channel);
        Long push = ofList.rightPush("expandCh", "qb-channel:" + ch);
        if (push > 0) {
            ResultVo success = ResultVoUtil.success("添加成功");
            success.setData("submit[refresh]");
            return success;
        } else {
            ResultVo success = ResultVoUtil.error("系统打盹中....");
            return success;
        }
    }


    @RequestMapping(value = "/index")
    @RequiresPermissions("mains:expandCh:index")
    public ModelAndView getAllExpandCh() {
        ListOperations<String, Object> ofList = redisTemplate.opsForList();
        List<Object> range = ofList.range("expandChannelParent", 0, ofList.size("expandChannelParent"));
        ArrayList<ExpandChannel> list = new ArrayList<>();
        ModelAndView view = new ModelAndView();
        view.setViewName("/mains/expand/index");
        if (range == null) {
            view.addObject("list", null);
        } else {
            HashOperations<String, Object, Object> ofHash = redisTemplate.opsForHash();

            for (Object o : range) {
                ExpandChannel ex = (ExpandChannel) o;
                Map<Object, Object> entries = ofHash.entries("qb-channel:" + ex.getCh());
                Set<Map.Entry<Object, Object>> set = entries.entrySet();
                long ouv = 0;
                long opv = 0;
                for (Map.Entry<Object, Object> objectEntry : set) {
                    Object value = objectEntry.getValue();
                    List<SourceFrom> source = (List<SourceFrom>) value;
                    long pv = source.stream().filter(st -> st.getType().equals(ex.getType())).count();
                    long uv = source.stream().filter(st -> st.getType().equals(ex.getType())).map(st -> st.getId()).distinct().count();
                    opv += pv;
                    ouv += uv;
                }
                ex.setUv(ouv);
                ex.setPv(opv);
                list.add(ex);
            }
            view.addObject("list", list);
        }
        return view;
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    public String toAdd() {
        return "/mains/expand/add";
    }


    @RequestMapping(value = "detail/pv/{type}/{id}")
    public ModelAndView getDetailPv(@PathVariable("type") String type,@PathVariable("id") String id) {
        HashOperations<String, Object, Object> ofHash = redisTemplate.opsForHash();
        Map<Object, Object> entries = ofHash.entries("qb-channel:" + id);
        Set<Map.Entry<Object, Object>> set = entries.entrySet();
        ArrayList<ExpandCh> list = new ArrayList<>();
        for (Map.Entry<Object, Object> objectEntry : set) {
            ExpandCh ch = new ExpandCh();

            Object key = objectEntry.getKey();
            Object value = objectEntry.getValue();
            List<SourceFrom> source = (List<SourceFrom>) value;
            long pv = source.stream().filter(s ->s.getType().equals(type)).count();
            ch.setDates((String) key);
            ch.setNums(pv);
            list.add(ch);
        }
        ModelAndView view = new ModelAndView();
        view.setViewName("/mains/expand/detailPv");
        view.addObject("list", list);
        return view;
    }

    @RequestMapping(value = "detail/uv/{type}/{id}")
    public ModelAndView getDetailUv(@PathVariable("type") String type,@PathVariable("id") String id) {
        HashOperations<String, Object, Object> ofHash = redisTemplate.opsForHash();
        Map<Object, Object> entries = ofHash.entries("qb-channel:" + id);
        Set<Map.Entry<Object, Object>> set = entries.entrySet();
        ArrayList<ExpandCh> list = new ArrayList<>();
        for (Map.Entry<Object, Object> objectEntry : set) {
            ExpandCh ch = new ExpandCh();

            Object key = objectEntry.getKey();
            Object value = objectEntry.getValue();
            List<SourceFrom> source = (List<SourceFrom>) value;
            long pv = source.stream().filter(s ->s.getType().equals(type)).map(st -> st.getId()).distinct().count();
            ch.setDates((String) key);
            ch.setNums(pv);
            list.add(ch);
        }
        ModelAndView view = new ModelAndView();
        view.setViewName("/mains/expand/detailUv");
        view.addObject("list", list);
        return view;
    }

}
